package com.fortune.rainshine.controller;

import com.fortune.rainshine.feign.service.ShopFeign;
import com.fortune.rainshine.feign.system.UserFeign;
import com.fortune.rainshine.feign.system.UserFeignNoTokken;
import com.fortune.rainshinecommon.base.MsgModel;
import com.fortune.rainshinecommon.enums.ResultCode;
import com.fortune.rainshinecommon.model.ShopModel;
import com.fortune.rainshinecommon.model.system.Role;
import com.fortune.rainshinecommon.model.system.User;
import com.fortune.rainshinecommon.query.ShopQuery;
import com.fortune.rainshinecommon.query.UserQuery;
import com.google.common.collect.Lists;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.util.*;

@RestController
@RequestMapping("userController")
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserFeign userFeign;
    @Autowired
    private ShopFeign shopFeign;
//    @Autowired
//    private UserFeignNoTokken userFeignNoTokken;

    @ResponseBody
    @RequestMapping("/generateAccount")
    public MsgModel generateAccount(@RequestBody ShopQuery query){
        try{
            return new MsgModel(ResultCode.SUCCESS, generateName(query.getUserId(), query.getShopId()));
        }catch (Exception e){
            logger.error("generateAccount ====> {}", e);
            return new MsgModel("生成店员帐号异常", ResultCode.FAILURE);
        }
    }

    @ResponseBody
    @RequestMapping("/addShopAssistant")
    public MsgModel addShopAssistant(@RequestBody UserQuery query){
        ServletRequestAttributes attributes=(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request=attributes.getRequest();
        String userId = request.getHeader("userId");
        try {
//            if(StringUtils.isBlank(query.getUsername())){
//                return new MsgModel("请输入帐号", ResultCode.FAILURE);
//            }
            if(StringUtils.isBlank(query.getNickName())){
                return new MsgModel("请输入姓名", ResultCode.FAILURE);
            }
            if(StringUtils.isBlank(query.getPhone())){
                return new MsgModel("请输入电话", ResultCode.FAILURE);
            }
            List<User> userList = userFeign.getUsersByPhone(query.getPhone());
            if(!userList.isEmpty()){
                return new MsgModel("此电话已存在", ResultCode.FAILURE);
            }
            if(query.getShopId() == null){
                return new MsgModel("请选择店面", ResultCode.FAILURE);
            }
            ShopModel shopModel = shopFeign.getShopByShopId(query.getShopId());
            if(shopModel == null || shopModel.getShopLevel() != 3){
                return new MsgModel("此店面不存在", ResultCode.FAILURE);
            }
            if(shopModel.getManagerId() != Integer.valueOf(userId)){
                return new MsgModel("无此权限", ResultCode.FAILURE);
            }
//            List<User> saList = userFeign.getShopAssistantsByShopId(Integer.valueOf(userId));
            List<User> saList = userFeign.getShopAssistantsByShopId(query.getShopId());
            if(!saList.isEmpty() && saList.size() >= 5){
                return new MsgModel("门店最多招聘5名店员", ResultCode.FAILURE);
            }

            List<Role> roles = new ArrayList<>();
            Role role = new Role(3);
            roles.add(role);
            User user = new User();
            user.setShopId(query.getShopId());
//            user.setUsername(query.getUsername());
            user.setUsername(generateName(Integer.valueOf(userId), query.getShopId()));
            user.setAvatar(query.getAvatar());
            user.setPhone(query.getPhone());
            user.setNickName(query.getNickName());
            user.setSex(query.getSex());
            user.setCreateId(Integer.valueOf(userId));
            user.setUpdateId(Integer.valueOf(userId));
            user.setRoles(roles);
            user.setPassword("123456");
            user.setCreateTime(new Date());
            user.setUpdateTime(new Date());
            return userFeign.add(user);
        } catch (Exception e){
            logger.error("addShopAssistant ====> {}", e);
            return new MsgModel("添加店员异常", ResultCode.FAILURE);
        }
    }

    @ResponseBody
    @RequestMapping("/getShopAssistants")
    public MsgModel getShopAssistants(@RequestBody ShopQuery query){
        if(query.getShopId() == null){
            return new MsgModel("门店状态异常", ResultCode.FAILURE);
        }
        ShopModel shop = shopFeign.getShopByShopId(query.getShopId());
        if(Objects.isNull(shop)){
            return new MsgModel("此门店不存在", ResultCode.FAILURE);
        }
        List<User> users = Optional.ofNullable(userFeign.getShopAssistantsByShopId(query.getShopId())).orElse(Lists.newArrayList());
        return new MsgModel(users.size(), users);
    }

    private String generateName(Integer userId, Integer shopId){
        User user = userFeign.getUserById(userId);
        List<User> users = userFeign.getAllAssistantsByShopId(shopId);
        String name;
        if(users.isEmpty()) {
            name = user.getUsername() + shopId + "001";
        }else{
            List<Integer> exampleNames = new ArrayList<>();
            DecimalFormat df = new DecimalFormat("000");
            for(User u : users){
                int length = u.getUsername().length();
                int j = Integer.parseInt(u.getUsername().substring(length-3, length));
                exampleNames.add(j);
            }
            int num = Collections.max(exampleNames) + 1;
            name = user.getUsername() + shopId + df.format(num);
        }
        return name;
    }

    @ResponseBody
    @RequestMapping("/getAllShopUsers")
    public MsgModel getAllShopUsers(@RequestBody ShopQuery query){
        if(query.getShopId() == null){
            return new MsgModel("门店状态异常", ResultCode.FAILURE);
        }
        ShopModel shop = shopFeign.getShopByShopId(query.getShopId());
        if(Objects.isNull(shop)){
            return new MsgModel("此门店不存在", ResultCode.FAILURE);
        }
        List<User> users = Optional.ofNullable(shopFeign.getAllUsersByShopId(query.getShopId())).orElse(Lists.newArrayList());
        return new MsgModel(users.size(), users);
    }
}
